<template>
  <el-card>
    <template #header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="'/home'">首页</el-breadcrumb-item>
        <el-breadcrumb-item>发布文章</el-breadcrumb-item>
      </el-breadcrumb>
    </template>
    <el-form label-width="100px" :model="form" :rules="rules" ref="form">
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      <el-form-item label="频道" prop="channel_id">
        <PinDao :form="form"></PinDao>
      </el-form-item>

      <el-form-item label="封面" prop="cover">
        <el-radio-group v-model="form.cover.type" @change="radioChange">
          <el-radio :label="1">单图</el-radio>
          <el-radio :label="3">三图</el-radio>
          <el-radio :label="0">无图</el-radio>
          <el-radio :label="-1">自动</el-radio>
        </el-radio-group>
        <div v-if="bol">
          <el-upload
            :file-list="fileList"
            v-if="form.cover.type > 0"
            :action="baseUrl + '/v1_0/upload'"
            name="image"
            :on-success="onSuccess"
            :before-upload="beforeUpload"
            :limit="form.cover.type"
            :on-remove="onRemove"
            list-type="picture-card"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <quillEditor
          v-model="form.content"
          @change="editorChange"
        ></quillEditor>
      </el-form-item>
      <el-form-item>
        <div v-if="!$route.query.id">
          <el-button @click="submit(false)" type="primary">发布文章</el-button>
          <el-button @click="submit(true)">存入草稿</el-button>
        </div>
        <div v-else>
          <el-button @click="edit(false)" type="primary">修改文章</el-button>
          <el-button @click="edit(true)">存入草稿</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { mpArticlesPost, mpArticlesGet, mpArticlesPut } from '@/api/index.js'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      baseUrl: process.env.VUE_APP_URL,
      bol: true,
      form: {
        title: '',
        content: '',
        cover: {
          type: 1,
          images: []
        },
        channel_id: ''
      },
      rules: {
        title: [{ required: true, message: '必填', trigger: 'blur' }],
        content: [{ required: true, message: '必填', trigger: 'change' }],
        cover: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (value.type > 0) {
                value.images.length === value.type
                  ? callback()
                  : callback(new Error(`请上传${value.type}`))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        channel_id: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },

  computed: {
    fileList () {
      return this.form.cover.images.map(item => {
        return { url: item }
      })
    }
  },
  created () {
    // 有id才有用
    if (this.$route.query.id) {
      this.getInfo()
    }
  },
  methods: {
    // 上传图片成功
    onSuccess (res) {
      // res就是响应数据
      this.form.cover.images.push(res.data.url)
      // 触发一次校验  是cover
      this.$refs.form.validateField(['cover'])
    },
    // radio修改时执行
    radioChange () {
      // 重置数据
      this.form.cover.images = []
      // 重置组件
      this.$refs.upload && this.$refs.upload.clearFiles()
      // 自己再次校验
      this.$refs.form.validateField(['cover'])
      //静默刷新 组件回到初始状态
      this.bol = false
      this.$nextTick(() => {
        this.bol = true
      })
    },
    // 上传前的限制
    beforeUpload (file) {
      const isImage = file.type === 'image/png' || file.type === 'image/jpeg'
      const isLimit2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.error('请上传png与jpeg格式图片')
      }
      if (!isLimit2M) {
        this.$message.error('请上传2M图片')
      }
      return isImage && isLimit2M
    },
    // 删除文件
    onRemove (file) {
      // 主动：删除images数组中对应的图片
      // 1.发布的时候 file 中保存了之前上传图片响应的信息 response.data.url 图片地址
      // 2.编辑的时候 file-list 属性，导致file就是{url:'xxxxxxx'}
      // 根据这个图片地址找到images对应的索引，通过splice(索引,1) 删除图片
      const _index = this.form.cover.images.findIndex(item => item === file.url)
      console.log(_index)
      this.form.cover.images.splice(_index, 1)
      // 自己再次校验
      // this.$refs.form.validateField(['cover'])
    },
    // 封面 校验内容
    editorChange () {
      // 触发content校验
      this.$refs.form.validateField(['content'])
    },
    submit (bol) {
      this.$refs.form.validate(async valid => {
        // console.log(valid)
        if (valid) {
          const res = await mpArticlesPost(this.form, bol)
          this.$message.success(bol ? '存储草稿成功' : '发表文章成功')
          this.$router.push('/article')
          console.log(res)
        }
      })
    },
    // 通过id获取详情
    async getInfo () {
      const res = await mpArticlesGet(this.$route.query.id)
      this.form = res.data
      // console.log(res)
    },
    // 编辑
    edit (bol) {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const res = await mpArticlesPut(this.form, bol)
          this.$message.success(bol ? '修改草稿成功' : '修改文章成功')
          this.$router.push('/article')
          console.log(res)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .ql-editor {
  min-height: 150px;
}
</style>
